import {Component, ElementRef, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {CustomService} from "../../services/custom.service";
import {AlertService} from "../../services/alert.service";
import {Message} from "../../model/Message";
import {delay, interval, Observable, retryWhen, Subject, take} from "rxjs";
import {CallcenterService} from "../../services/callcenter.service";
import {WebSocketSubject} from "rxjs/internal/observable/dom/WebSocketSubject";
import {webSocket} from "rxjs/webSocket";
import {MessageVo} from "../../vo/MessageVo";

@Component({
  selector: 'app-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit,OnDestroy {
  ml: Array<MessageVo>;
  socket$: any;
  msgtext: string;
  WS_ENDPOINT = "ws://192.168.2.66:2066/callcenter";
  sendping$:any;
  myuserid:string;
  mynickname:string;
  inputtext:string;
  onMessgeIn:Subject<any>;

  @ViewChild('scrollMe') private myScrollContainer: ElementRef;

  constructor(private customservice:CustomService,
              private alertservice:AlertService,
              private callservice: CallcenterService) {
    this.ml = new Array<MessageVo>();
    this.onMessgeIn=new Subject<any>();
  }

  ngOnInit(): void {
    // console.log('userid'+this.customservice.userid);
    // console.log('token'+this.customservice.token);
    this.myuserid=this.customservice.userid

    this.init();

    this.onMessgeIn
      .subscribe(()=>{
        this.scrollToBottom()
      })
  }


  private async getNewWebSocket() :Promise<WebSocketSubject<any>>{
    //console.log('条件触发');
    return webSocket({url:this.WS_ENDPOINT,
      deserializer:({data})=>{
        let m=new Message();
        // console.log(data);
        m=JSON.parse(data)
        return m;
      }
      //closeObserver:(event:any)=>this.closeedConnect()
    });

  }


  init(){
    if (!this.socket$ || this.socket$.closed){
      this.getNewWebSocket()
        .then((data:any)=>{
          if(data){
            this.socket$=data;
            this.socket$
              .pipe(
                retryWhen(errors => errors.pipe(delay(1000), take(2))),
              )
              .subscribe((m:Message)=>{
                //console.dir(m);
                let type=m.type;
                switch (type){
                  case "REGIST":
                    console.log('regist');
                    console.dir(m)
                    //this.myuserid=m.fromuserid;
                    this.mynickname=m.nickname;
                    this.customservice.token=m.token;
                    this.pullMessageList('7b0b3bed2e3145be9c6206789620c766')
                    break;
                  case "PING":
                    console.log('before   '+this.customservice.token);
                    this.customservice.token=m.token;
                    console.log('after  '+this.customservice.token);
                    break;

                  case "MESSAGE":

                   // console.dir(m);
                    if(m.talkid){
                      this.pullMessage(m.talkid);
                    }

                    break;

                  case "NEWMESSAGE":
                   // console.dir(m);
                    if(m.messageVo){
                      this.ml.push(m.messageVo)

                      this.onMessgeIn.next('single');
                    }
                    break;

                  case "MESSAGELIST":
                    this.ml=new Array<MessageVo>();
                    this.ml=m.msgvolist;
                    this.onMessgeIn.next('list');
                    break
                }





               // this.ml.push(m);
              })

            this.sendping$=interval(6*60*1000)
              .subscribe(()=>{
                this.sendping()
              })

            this.sendRegist();

          }
        })
    }
  }

  sendping(){
    let msg = new Message();
    msg.type = 'PING';
    msg.fromuserid = this.customservice.userid;
    msg.token=this.customservice.token;
    this.socket$.next(msg)

  }

  sendRegist(){
    let msg=new Message();
    msg.type='REGIST';
    msg.fromuserid=this.customservice.userid;
    msg.token=this.customservice.token;
    this.socket$.next(msg);
  }

  ngOnDestroy(): void {
    if(this.socket$!=null&&!this.socket$.closed){
      this.socket$.complete();
      this.sendping$.complete();
    }
  }


  pullMessage(talkid:string){
    let msg=new Message();
    msg.type='PULLMSG';
    msg.fromuserid=this.customservice.userid;
    msg.token=this.customservice.token;
    msg.talkid=talkid;
    this.socket$.next(msg);
  }


  pullMessageList(talkid:string){
    let msg=new Message()
    msg.type="PULLMSGLIST";
    msg.fromuserid=this.customservice.userid;
    msg.token=this.customservice.token;
    msg.talkid=talkid;
    this.socket$.next(msg);
  }

  sendTextMessage(){
    let msg=new Message();
    msg.type='MESSAGE';
    msg.fromuserid=this.myuserid;
    msg.content=this.inputtext;
    msg.token=this.customservice.token;
    msg.nickname=this.mynickname
    msg.touserid='admin'
    this.socket$.next(msg);

  }


  scrollToBottom(): void {
    //document.getElementById('scrollMe'?).scroll(0,666)
    try {
      setTimeout(()=>{
        this.myScrollContainer.nativeElement.scroll(0,this.myScrollContainer.nativeElement.scrollHeight);
      },200)
    } catch(err) { }
  }





}
